#include "StdAfx.h"
#include "TimerThread.h"
#include "Timer.h"

namespace WTB{

	unsigned int CTimerThread::run()
	{

		while(!m_pTimer->IsExit())
		{
			TMilliSecond timer;
			if (m_pTimer->FindEventTimer(timer) == -1)
			{
				printf("thread: %d wait for timer add.\n",m_unThreadId);
				m_pKernelEvent->Wait();
			}else
			{
				printf("thread: %d wait timer: %d.\n",m_unThreadId,timer);
				m_pKernelEvent->Wait(timer);
			}

			m_pTimer->ExpireEventTimer();
		}

		printf("thread: %d exit.\n",m_unThreadId);
		return 0;
	}

	int CTimerThreads::Create(CTimer* _pEventTimer, int _nEventTimerThreadAmount)
	{


		m_nEventTimerThreadAmount = _nEventTimerThreadAmount;

		m_pArrKernelEvents = new CKernelEvent[m_nEventTimerThreadAmount];
		m_pArrEventTimerThreads = new CTimerThread[m_nEventTimerThreadAmount];

		for (int nIndex = 0; nIndex < m_nEventTimerThreadAmount; ++nIndex)
		{
			m_pArrKernelEvents[nIndex].Create(false,false,"");
			m_pArrEventTimerThreads[nIndex].Create(_pEventTimer,&m_pArrKernelEvents[nIndex]);
		}

		return 0;
	}

	void CTimerThreads::Close()
	{
		for (int nIndex = 0; nIndex < m_nEventTimerThreadAmount; ++nIndex)
		{
			m_pArrKernelEvents[nIndex].Set();
			m_pArrEventTimerThreads[nIndex].WaitForRoutineEnd();
			m_pArrEventTimerThreads[nIndex].Close();
			m_pArrKernelEvents[nIndex].Close();
		}

		if (NULL != m_pArrEventTimerThreads)
		{
			delete []m_pArrEventTimerThreads;
			m_pArrEventTimerThreads = NULL;
		}

		if (NULL != m_pArrKernelEvents)
		{
			delete []m_pArrKernelEvents;
			m_pArrKernelEvents = NULL;
		}

		m_nEventTimerThreadAmount = 0;

	}

}